import {Component, OnInit} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Chero} from '../../model/chero';
import {CheroService} from '../../service/cheroService/chero.service';
import {ActivatedRoute, Params, Router} from '@angular/router';
import 'rxjs/add/operator/switchMap';
@Component({
  selector: 'app-crisislist',
  template: `
    <ul class="items">
      <li *ngFor="let crisis of crises | async"
          (click)="onSelect(crisis)"
          [class.selected]="isSelected(crisis)">
        <span class="badge">{{ crisis.id }}</span>
        {{ crisis.name }}
      </li>
    </ul>

    <router-outlet></router-outlet>`,
  styleUrls: ['./crisislist.component.css']
})
export class CrisislistComponent implements OnInit {
  crises: Observable<Chero[]>;
  selectedId: number;

  constructor(private cheroService: CheroService, private activatedRoute: ActivatedRoute, private router: Router) {
  }

  isSelected(crises: Chero) {
    return crises.id === this.selectedId;
  }

  ngOnInit() {
    this.crises = this.activatedRoute.params
      .switchMap((params: Params) => {
        this.selectedId = +params['id'];
        return this.cheroService.getCHeros();
      });
  }

  onSelect(crisis: Chero) {

    this.selectedId = crisis.id;
    this.router.navigate([crisis.id], {relativeTo: this.activatedRoute})
  }
}
